import {
  getSongDetail,
  getWord
} from "../../network/player"
import songWord from "../../utils/song"
import {
  playStore
} from "../../store/player"
const app = getApp()
const audio = wx.createInnerAudioContext({})
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    currentSong: {}, //当前歌曲
    word: "", //所有歌词
    danWord: "", //单句歌词
    danWordIndex: 0, //控制单句歌词赋值频率
    currentSwiper: 0, //当前轮播哪页
    swiperHeigth: 0, //可轮播的高度
    pageTitles: ['歌曲', '歌词'],
    endTime: 0, //歌曲总事件，
    currentTime: 0, //歌曲当前播放时间
    progress: 0, //进度条,100则全
    waiting: false, //节流，解决进度条偶尔跳一下的问题
    isplay: true, //判断点击是暂停还是播放
    scrollHeight: 0, //歌词页面歌词滚动的高度
    songIndex: 0, //歌曲索引
    songList: [], //歌曲列表
    mode: 0, //0顺序播放，1单曲循环，2随机播放
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 切换播放模式
  changeMode() {
    let mode = this.data.mode + 1;
    if (mode == 3) mode = 0;
    // 设置是否是单曲循环
    if(mode===1){
      audio.loop=true
    }else{
      audio.loop=false
    }
    this.setData({
      mode
    })
    //  console.log(mode);
  },
  onLoad(options) {
    // console.log(options.id);
    this.setData({
      id: options.id
    })
    // 因为自定义获取设备信息
    this.setData({
      swiperHeigth: app.globalData.swiperHeight
    })
    this.bus()
    // 监听音频播放进度更新事件
    audio.onTimeUpdate(() => {
      // console.log(audio.currentTime);
      if (!this.data.waiting) {
        this.setData({
          currentTime: audio.currentTime * 1000
        })
        this.setData({
          progress: this.data.currentTime / this.data.endTime * 100
        })
        // 歌词展示
        let index = this.data.word.findIndex((val) => {
          return val.times > audio.currentTime * 1000
        })
        if (index == -1) {
          index = this.data.word.length - 1
        } else {
          index = index - 1
        }
        // console.log(index);
        if (index === this.data.danWordIndex) return
        this.setData({
          danWord: this.data.word[index].words,
          danWordIndex: index,
          scrollHeight: this.data.danWordIndex * 35
        })
      }
    })
    playStore.onStates(["playSongList", "playIndex"], this.playSongList);
    audio.onEnded(() => {
     if(audio.loop) return
     this.nextBtn()
    })
  },
  //拿到传过来的对应歌曲索引及整个歌单
  playSongList(value) {
    // console.log(value);
    if (value.playIndex) {
      this.setData({
        songIndex: value.playIndex,
      })
    }
    if (value.playSongList) {
      this.setData({
        songList: value.playSongList
      })
    }
  },
  // 控件上一首
  prevBtn() {
    let index = this.data.songIndex;
    let length = this.data.songList.length
    if (this.data.mode == 0) { //顺序播放
      index = index - 1;
      if (index == -1) index = length - 1;
    } else if (this.data.mode == 1) { //单曲循环
      audio.currentTime = 0
    } else {
      index = Math.floor(Math.random() * length); //单曲循环
    }
    let song = this.data.songList[index];
    // console.log(song.id);
    this.setData({
      id: song.id,
      songIndex: index
    });
    playStore.setState("playIndex", index)
    this.bus()
  },
  // 控件下一首
  nextBtn() {
    let index = this.data.songIndex;
    let length = this.data.songList.length;
    switch (this.data.mode) {
      case 1:
      case 0:
        index = index + 1;
        if (index == length) index = 0;
        break;
      case 2:
        index = Math.floor(Math.random() * length)
        break;
    }
    let song = this.data.songList[index];
    // console.log(song.id);
    this.setData({
      id: song.id,
      songIndex: index
    });
    playStore.setState("playIndex", index)
    this.bus()
  },
  // 音乐控件公共逻辑部分
  bus() {
    audio.src = `https://music.163.com/song/media/outer/url?id=${this.data.id}.mp3`
    audio.autoplay = true
    this.ongetSongDetail(this.data.id)
    this.ongetSongWord(this.data.id)
  },
  // 判断进度条控制歌曲播放时间
  seeProgress(e) {
    this.data.waiting = true;
    // setTimeout(() => {
    //   this.data.waiting = false;
    // },)
    wx.nextTick(()=>{
      this.data.waiting = false;
    })
    // console.log(e.detail.value);
    //进度条位置
    let newVal = e.detail.value;
    // 换算出歌曲当前播放时间
    const currentTime = newVal / 100 * this.data.endTime;
    //  要转换成秒
    audio.seek(currentTime / 1000);
    this.setData({
      currentTime
    })

    // 这两个函数是因为如果调节进度条，但是时间会卡住不动，这个是小程序bug,需要以下两个函数做个缓冲
    audio.onWaiting(() => {
      audio.pause()
    })
    audio.onCanplay(() => {
      audio.play()
    })
  },
  // 1.获取歌曲的详情
  async ongetSongDetail(id) {
    const res = await getSongDetail(id)
    // console.log(res);
    this.setData({
        currentSong: res.songs[0]
      }),
      // 歌曲总时间接口里面给了，当然也可以用我们设置的属性拿
      this.setData({
        endTime: this.data.currentSong.dt
      })
  },
  // 2.获取歌曲歌词
  async ongetSongWord(id) {
    const res = await getWord(id)
    // console.log(res);
    this.setData({
      word: songWord(res.lrc.lyric)
    })
    // console.log(this.data.word);
  },
  // 状态栏的判断
  ongetSwiper(e) {
    // console.log(e);
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  changePage(e) {
    this.setData({
      currentSwiper: e.target.dataset.index
    })
    // console.log(e.target.dataset.index);
  },
  // 控制播放暂停歌曲
  goPause() {
    if (this.data.isplay) {
      audio.pause();
      this.setData({
        isplay: false
      })
    } else {
      audio.play();
      this.setData({
        isplay: true
      })
    }
  },
  onUnload() {
    playStore.offStates(["playSongList", "playIndex"], this.playSongList)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})